<template>
  <div>
    <zz-tree
      ref="workerTree"
      :treeData="personProjectList"
      :options="workerOptions"
      @node-select="itemWorkerSelect"
      @node-arrow="itemWorkerDepartClick"
      @node-click="itemWorkerClick"
    ></zz-tree>

    <editProject
      @success="editProjectSuccess"
      @close="projectVisible = false"
      :pjId="projectId"
      :visible="projectVisible"></editProject>

    <cooperator
      ref="cooperator"
      @close="cooperatorVisible = false"
      @success="getPersonProList"
      @doRelase="doRelaseCooperator"
      :pjId="projectId"
      :cooperatorId="cooperatorId"
      :visible="cooperatorVisible"></cooperator>

  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  export default {
    name: 'zz-worker',
    data () {
      return {
        url: {},
        projectId: '',
        cooperatorId: '',
        groupId: '',
        workerOptions: {
          halfCheckedStatus: true, // 控制父框是否需要半钩状态
          lazy: true,
          load: this.loadingChild
        },
        workers: [],
        keyword: '',
        projectVisible: false,
        cooperatorVisible: false,
        roleId: {
          1: '工人',
          2: '班组长',
          3: '工人'
        },
        personProjectList: []
      }
    },
    computed: {
      ...mapGetters({
        personProjectDefault: 'getPersonProjectDefault',
        currentUser: 'currentUser'
      })
    },
    props: {
      // 是否选择人员组件
      isRetrieve: {
        type: Boolean,
        default: false
      },
      // 是否开启过滤
      isFilter: {
        type: Boolean,
        default: false
      },
      // 过滤条件
      filterRule: '',
      // 是否开启全部工人选项
      isAllWorkers: {
        type: Boolean,
        default: true
      },
      // 是否打开参建各方 && 项目部成员
      isContact: {
        type: Boolean,
        default: false
      },
      // 是否加入参建各方
      isOpenContact: {
        type: Boolean,
        default: true
      },
      // 是否加入项目部成员
      isOpenProjectMember: {
        type: Boolean,
        default: true
      },
      // 是否获取劳务公司
      isCooperator: {
        type: Boolean,
        default: true
      },
      // 是否开启选择项目
      isChooseProject: {
        type: Boolean,
        default: false
      },
      // 是否开启选择劳务公司
      isChooseCooperator: {
        type: Boolean,
        default: false
      },
      // 是否开启直接选择班组
      isChooseGroup: {
        type: Boolean,
        default: false
      },
      // 是否开启操作数组
      isHandle: {
        type: Boolean,
        default: false
      },
      // 是否只显示有账号的工人
      isHasWorkerMid: {
        type: Boolean,
        default: false
      },
      // 项目部成员是加入项目负责人&& 项目部管理员
      isProjectManage: {
        type: Boolean,
        default: false
      },
      openWorkers: {
        type: Boolean,
        default: true
      },
      type: {
        type: String,
        default: 'choose'
      }
    },
    created () {
      this.url.syncProject = `${this.$site.projectServer}/front/syncProjectRetrieve/syncProject.htm`
      this.url.syncCooperator = `${this.$site.projectServer}/front/syncProjectRetrieve/syncCooperator.htm`
      this.url.syncGroup = `${this.$site.projectServer}/front/syncProjectRetrieve/syncGroup.htm`
      this.url.syncWorker = `${this.$site.projectServer}/front/syncProjectRetrieve/syncWorker.htm`
    },
    mounted () {
      this.getPersonProList()
    },
    methods: {
      // 获取项目列表
      getPersonProList () {
        this.$axios({
          method: 'post',
          url: this.url.syncProject,
          data: this.$qs.stringify({'query.authCheck': 1}, {indices: false})
        }).then(res => {
          if (res.data.errorMsg) {
            this.$message.error(res.data.errorMsg)
          } else {
            let list = []
            res.data.list.forEach((x, i) => {
              Object.assign(x, {label: x.project_title})
              Object.assign(x, {id: x.project_id})
              Object.assign(x, {isProject: true})
              Object.assign(x, {children: []})
              Object.assign(x, {openArr: this.isChooseProject})
              Object.assign(x, {showArr: false})
              if (this.isHandle) {
                Object.assign(x, {showSelect: false})
                Object.assign(x, {select: {1: '编辑', 2: '新增劳务公司'}})
              }
              this.$set(x, 'open', false)
              this.$set(x, 'checked', false)
              // 获取第一个项目下的工人
              if (i === 0 && (!this.isAllWorkers || this.isContact) && !this.isFilter) {
                x.checked = true
                this.projectId = x.project_id
                this.$emit('project', x)
                this.syncWorker()
              }
              // 过滤
              if (this.isFilter) {
                // 过滤条件
                if (parseInt(this.filterRule) === x.project_id) {
                  x.checked = false
                  x.open = true
                  this.projectId = x.project_id
                  this.$emit('project', x)
                  list.push(x)
                  if (this.isContact) {
                    this.syncProjectTeam({pjId: this.projectId, type: 2})
                  } else {
                    this.syncWorker()
                  }
                }
              } else {
                list.push(x)
              }
            })
            if (this.isAllWorkers) {
              this.personProjectList = [{
                label: '全体工人',
                open: true,
                checked: true,
                children: []
              }]
              this.personProjectList[0].children = []
              this.personProjectList[0].children = this.personProjectList[0].children.concat(list)
              this.syncWorker()
            } else {
              this.personProjectList = list.map((item) => {
                item.children = this.setProjectTeam(item.project_id)
                return item
              })
            }
          }
        })
      },
      setProjectTeam (projectId) {
        const items = []
        if (this.isOpenProjectMember && this.isContact) {
          items.push({
            label: '项目部成员',
            checked: this.isFilter, // 如果有过滤条件的话
            type: 2,
            children: [],
            isProjectOrganizeList: true,
            isProjectOrganize: true,
            pjId: projectId,
            project_id: projectId,
            isProjectMember: true
          })
        }
        if (this.isOpenContact && this.isContact) {
          items.push({
            label: '参建各方',
            checked: false,
            project_id: projectId,
            pjId: projectId,
            type: 5,
            isProjectTeam: true,
            isProjectTeamList: true,
            children: []
          })
        }
        if (this.isCooperator) {
          items.push({
            label: '劳务公司',
            project_title: '劳务公司',
            isAllCooperator: true,
            open: false,
            checked: false,
            project_id: projectId,
            pjId: projectId,
            isCooperator: true,
            children: []
          })
        }
        return items
      },
      async loadingChild (node) {
        // 获取项目部
        if (node.isProjectOrganizeList) {
          this.findProjectOrganizeList(node)
          return
        }
        // 获取项目部成员
        if (node.isProjectOrganizeListChild) {
          this.findProjectOrganizeListChild(node)
          return
        }
        // 获取参建各方
        if (node.isProjectTeamList) {
          this.findProjectTeamList(node)
          return
        }
        // 获取参建各方下的成员
        if (node.isProjectTeamListChild) {
          this.findProjectTeamListChild(node)
          return
        }
        // 获取劳务公司
        if (this.isCooperator && node.isCooperator) {
          let data = await new Promise((resolve) => {
            const data = {
              'cooperatorQuery.project_id': node.project_id
            }
            this.$axios({
              method: 'post',
              url: this.url.syncCooperator,
              data: this.$qs.stringify(data, {indices: false})
            }).then(res => {
              if (res.data.errorMsg) {
                this.$message.error(res.data.errorMsg)
              } else {
                let arr = res.data.list.map((x) => {
                  this.$set(x, 'checked', false)
                  Object.assign(x, {label: x.unit_name})
                  Object.assign(x, {id: x.cooperator_id})
                  Object.assign(x, {openArr: this.isChooseCooperator})
                  Object.assign(x, {textArr: '选择公司'})
                  Object.assign(x, {isCooperatorSon: true})
                  Object.assign(x, {showArr: false})
                  if (this.isHandle) {
                    Object.assign(x, {showSelect: false})
                    Object.assign(x, {select: {3: '编辑', 4: '删除'}})
                  }
                  return x
                })
                resolve(arr)
              }
            })
          })
          let tem = this.getParentNode(node, this.personProjectList)
          this.$set(tem, 'children', data)
          Promise.resolve(data)
        } else {
          // 获取班组
          let data = await new Promise((resolve, reject) => {
            const data = {
              'groupQuery.project_id': node.project_id,
              'groupQuery.cooperator_id': node.cooperator_id
            }
            this.$axios({
              method: 'post',
              url: this.url.syncGroup,
              data: this.$qs.stringify(data, {indices: false})
            }).then(res => {
              // Success handle
              if (res.data.errorMsg) {
                this.$message.error(res.data.errorMsg)
              } else {
                const arr = res.data.list.map((x) => {
                  this.$set(x, 'checked', false)
                  Object.assign(x, {label: x.name})
                  Object.assign(x, {id: x.group_id})
                  Object.assign(x, {isGroup: true})
                  Object.assign(x, {pjId: node.project_id})
                  Object.assign(x, {openArr: this.isChooseGroup})
                  Object.assign(x, {textArr: '选择班组'})
                  Object.assign(x, {showArr: false})
                  Object.assign(x, {closeLeaf: true})
                  return x
                })
                resolve(arr)
              }
            })
          })
          let tem = this.getParentNode(node, this.personProjectList)
          this.$set(tem, 'children', data)
          Promise.resolve(data)
        }
      },
      getParentNode (node, treeData) {
        let tem
        let postions = node.key.split('-')
        for (let [index, item] of postions.entries()) {
          switch (index) {
            case 0:
              break
            case 1:
              tem = treeData[item]
              break
            default:
              tem = tem.children[item]
          }
        }
        return tem
      },
      itemWorkerClick (item) {
        if (this.openWorkers) {
          // 项目部成员
          if (item.isProjectOrganize) {
            // 是否选人组件
            if (this.isRetrieve) {
              this.$emit('ProjectTeam', item)
              this.syncProjectTeam(item)
            } else {
              this.$emit('projectMember', item.pjId)
            }
            return
          }
          // 参建各方成员
          if (item.isProjectTeamList) {
            this.$emit('ProjectTeam', item)
            this.syncProjectTeam(item)
            return
          }
          if (item.isProjectTeamListChild) {
            this.$emit('ProjectTeamChild', item)
            this.syncProjectTeam(item)
            return
          }
          if (item.isProject || item.isAllCooperator) {
            this.$emit('project', item)
          }
          if (item.isCooperatorSon) {
            this.$emit('cooperator', item)
          }
          if (item.isGroup) {
            this.$emit('group', item)
          }
          this.projectId = item.pjId || item.project_id
          this.cooperatorId = item.cooperator_id
          this.groupId = item.group_id
          this.syncWorker()
        } else {
          this.itemWorkerDepartClick(item)
        }
      },
      setTreeData (x) {
        Object.assign(x, {label: x.name})
        Object.assign(x, {children: []})
        this.$set(x, 'open', false)
        this.$set(x, 'checked', false)
        if (this.showSelect) {
          this.$set(x, 'showSelect', this.showSelect)
          Object.assign(x, {select: {1: '新增', 2: '重命名', 3: '删除', 4: '上移', 5: '下移'}})
        }
      },
      // 获取项目部
      async findProjectOrganizeList (node) {
        let data = await this.findProjectOrganizeListAwait(node)
        let tem = this.getParentNode(node, this.personProjectList)
        this.$set(tem, 'children', data)
      },
      findProjectOrganizeListAwait (node) {
        return new Promise((resolve) => {
          const data = {
            'query.project_id': node.pjId
          }
          this.$axios({
            method: 'post',
            url: `${this.$site.projectServer}/front/person/findProjectOrganizeList.htm`,
            data: this.$qs.stringify(data, {indices: false})
          }).then(res => {
            if (res.data.errorMsg) {
              this.$message.error(res.data.errorMsg)
            } else {
              const arr = []
              const {list} = res.data
              list.forEach((item) => {
                if (!item.parentId) {
                  Object.assign(item, {isProjectOrganizeListChild: true})
                  Object.assign(item, {isProjectOrganize: true})
                  Object.assign(item, {type: 2})
                  this.setTreeData(item)
                  arr.push(item)
                }
              })
              this.projectPerson = res.data.list
              const unallocated = {
                label: '未分配',
                closeLeaf: true,
                unallocated: true,
                type: 2,
                organizeId: 0,
                isProjectOrganize: true,
                isProjectOrganizeListChild: true
              }
              this.$set(unallocated, 'checked', false)
              arr.push(unallocated)
              resolve(arr)
            }
          })
        })
      },
      // 获取项目部下的子部门
      async findProjectOrganizeListChild (node) {
        let data = await new Promise((resolve) => {
          const arr = []
          this.projectPerson.forEach(item => {
            if (item.parentId === node.organizeId) {
              Object.assign(item, {isProjectOrganizeListChild: true})
              Object.assign(item, {isProjectOrganize: true})
              Object.assign(item, {type: 2})
              this.setTreeData(item)
              arr.push(item)
            }
          })
          resolve(arr)
        })
        let tem = this.getParentNode(node, this.personProjectList)
        this.$set(tem, 'children', data)
      },
      // 获取参建各方
      async findProjectTeamList (node) {
        let data = await this.findProjectTeamListAwait(node)
        let tem = this.getParentNode(node, this.personProjectList)
        this.$set(tem, 'children', data)
      },
      findProjectTeamListAwait (node) {
        return new Promise(resolve => {
          const data = {
            'query.project_id': node.pjId
          }
          this.$axios({
            method: 'post',
            url: `${this.$site.projectServer}/front/person/findProjectTeamList.htm`,
            data: this.$qs.stringify(data, {indices: false})
          }).then(res => {
            if (res.data.errorMsg) {
              this.$message.error(res.data.errorMsg)
            } else {
              const arr = []
              res.data.list.forEach(item => {
                if (!item.parentId) {
                  Object.assign(item, {isProjectTeamListChild: true})
                  Object.assign(item, {isProjectTeam: true})
                  Object.assign(item, {item: 5})
                  this.setTreeData(item)
                  arr.push(item)
                }
              })
              this.projectTeam = res.data.list
              const unallocated = {
                label: '未分配',
                closeLeaf: true,
                unallocated: true,
                type: 5,
                teamId: 0,
                isProjectTeam: true,
                isProjectTeamListChild: true
              }
              this.$set(unallocated, 'checked', false)
              arr.push(unallocated)
              resolve(arr)
            }
          })
        })
      },
      // 获取参建各方下的成员
      async findProjectTeamListChild (node) {
        let data = await new Promise((resolve) => {
          const arr = []
          this.projectTeam.forEach(item => {
            if (item.parentId === node.organizeId) {
              Object.assign(item, {isProjectTeamListChild: true})
              Object.assign(item, {isProjectTeam: true})
              Object.assign(item, {type: 5})
              this.setTreeData(item)
              arr.push(item)
            }
          })
          resolve(arr)
        })
        let tem = this.getParentNode(node, this.personProjectList)
        this.$set(tem, 'children', data)
      },
      syncWorker () {
        const data = {
          'workerQuery.project_id': this.projectId,
          'workerQuery.cooperator_id': this.cooperatorId,
          'workerQuery.group_id': this.groupId,
          'workerQuery.type': this.isHasWorkerMid ? 2 : 1,
          'workerQuery.keyword': this.keyword
        }
        this.$axios({
          method: 'post',
          url: this.url.syncWorker,
          data: this.$qs.stringify(data, {indices: false})
        }).then(res => {
          if (res.data.errorMsg) {
            this.$message.error(res.data.errorMsg)
          } else {
            this.workers = res.data.list.map((x) => {
              this.$set(x, 'choose', false)
              this.$set(x, 'mid', x.member_id || x.worker_id)
              this.$set(x, 'roleName', this.roleId[x.role_id])
              return x
            })
            this.$emit('workers', this.workers, res.data.query)
          }
        })
      },
      syncProjectTeam (node) {
        const data = {
          'query.project_id': node.pjId,
          'query.organize_id': node.organizeId,
          'query.team_id': node.teamId,
          'query.type': node.type
        }
        this.$axios({
          method: 'post',
          url: `${this.$site.projectServer}/front/person/findProjectManList.htm`,
          data: this.$qs.stringify(data, {indices: false})
        }).then(res => {
          if (res.data.errorMsg) {
            this.$message.error(res.data.errorMsg)
          } else {
            if (res.data.list) {
              this.workers = res.data.list.map((x) => {
                this.$set(x, 'choose', false)
                this.$set(x, 'mid', x.member_id || x.worker_id)
                this.$set(x, 'name', x.member_name || x.worker_id)
                return x
              })
              this.$emit('workers', this.workers, res.data.query)
            }
          }
        })
      },
      // 选择班组
      itemWorkerDepartClick (item) {
        if (this.type === 'click') {
          this.clickHanled(item)
        } else if (this.type === 'retrieve') {
          if (item.isProject && !this.isChooseProject) {
            return
          }
          if (item.isCooperator && !this.isChooseCooperator) {
            return
          }
          this.$emit('setGroup', item)
        }
      },
      // 搜索工人
      searchWorker (keyword) {
        this.keyword = keyword
        this.syncWorker()
      },
      doRelaseCooperator () {
        this.cooperatorId = ''
        this.getPersonProList()
      },
      itemWorkerSelect (option) {
        const {key, value} = option
        switch (Number.parseInt(key)) {
          // 编辑项目
          case 1:
            this.projectId = value.project_id
            this.projectVisible = true
            break
          // 新增劳务公司
          case 2:
            this.cooperatorId = ''
            this.projectId = value.project_id
            this.cooperatorVisible = true
            break
          // 编辑劳务公司
          case 3:
            this.cooperatorId = value.cooperator_id
            this.cooperatorVisible = true
            break
          // 删除劳务公司
          case 4:
            this.cooperatorId = value.cooperator_id
            this.$refs.cooperator.delCooperator()
            break
        }
      },
      editProjectSuccess (projectName) {
        for (let item of this.personProjectList) {
          if (item.pjId === this.projectId) {
            item.label = projectName
            break
          }
        }
      }
    }
  }
</script>
